package com.rainsoftware.LicenseSystem.models.entity;

import com.rainsoftware.LicenseSystem.models.entity.base.BaseEntity;
import gaarason.database.annotation.Column;
import gaarason.database.annotation.Table;
import java.time.LocalDateTime;
import java.util.Random;

import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import lombok.experimental.Accessors;
import org.json.JSONObject;
import org.springframework.stereotype.Repository;


@Data
@ToString(callSuper = true)
@Accessors(chain = true)
@EqualsAndHashCode(callSuper = true)
@Table(name = "licensekeys")
public class LicenseKey extends BaseEntity {
    private static final int KeyLength = 18;
    private static final long serialVersionUID = 1L;

    /** auto generator start **/

    @Column(name = "license_key", length = 512L)
    private String licenseKey;

    @Column(name = "developer_id", nullable = true)
    private Integer developerId;

    @Column(name = "product_id", nullable = true)
    private Integer productId;

    @Column(name = "machine", length = 256L)
    private String machine;

    @Column(name = "activated")
    private Boolean activated;

    @Column(name = "created_at", nullable = true)
    private LocalDateTime createdAt;

    //不再需要 expire_time, 此字段可以通过计算得出
    @Column(name = "activated_at", nullable = true)
    private LocalDateTime activatedAt;

    @Column(name = "duration")
    private Long duration;

    @Repository
    public static class Model extends BaseEntity.BaseModel<LicenseKey, Integer> {

    }
    public JSONObject toJson() {
        return new JSONObject()
                .put("id", getId())
                .put("license_key", licenseKey)
                .put("activated", activated)
                .put("created_at", getCreatedAt())
                .put("duration", duration)
                .put("product_id", productId)
                .put("developer_id", developerId)
                .put("activated_at", activated ? activatedAt.toString() : "");
    }

    public static String generateUniqueKey() {
        String SALTCHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
        StringBuilder salt = new StringBuilder();
        Random rnd = new Random();
        int cnt_tot = 0, cnt_char = 0;
        while (cnt_tot < KeyLength) {
            if (cnt_char == 6) {
                salt.append('-');
                cnt_char = 0;
            } else {
                int index = rnd.nextInt(SALTCHARS.length()); // Improved random index generation
                salt.append(SALTCHARS.charAt(index));
                cnt_char++;
                cnt_tot++;
            }
        }
        return salt.toString();
    }
}